<template>
  <view class="vm-page bg-efefef vh">
    <!-- 列表 -->
    <view class="common-form">
      <view class="no-data" v-if="devices.length == 0">{{
        searching ? "未找到设备" : "点击下方按钮开始搜索设备"
      }}</view>

      <view class="dev-list" v-else>
        <view
          class="dev-item"
          v-for="dev in devices"
          :key="dev.deviceId"
          @click="connectDevice(dev)"
        >
          <nut-row>
            <nut-col :span="22">
              <view class="dev-name">{{
                dev.name ? dev.name : "未知设备"
              }}</view>
              <view class="dev-id">{{ dev.deviceId }}</view>
              <view class="dev-signal"
                >信号：{{ dev.RSSI ? dev.RSSI : "---" }}</view
              >
              <view class="dev-service" v-if="dev.advertisServiceUUIDs"
                >服务：{{
                  dev.advertisServiceUUIDs.length === 1
                    ? "1 service"
                    : dev.advertisServiceUUIDs.length + " services"
                }}</view
              >
            </nut-col>
            <nut-col :span="2"
              ><nut-icon
                class="dev-next"
                name="arrow-right"
                color="#ccc"
              ></nut-icon>
            </nut-col>
          </nut-row>
        </view>
      </view>
    </view>
    <!-- 底部搜索按钮 -->
    <view class="common-form-btns">
      <nut-button
        :loading="searching"
        type="primary"
        block
        plain
        @tap="doSearch"
        >{{ searching ? "停止搜索" : "开始搜索" }}</nut-button
      >
    </view>
  </view>
</template>

<script lang="ts">
import Taro from "@tarojs/taro";
import { set, get } from "@/utils/storage";
import {
  BTManager,
  ConnectStatus,
  SuccessCallbackEvent,
} from "@/components/wx-ant-ble/index";

export default {
  name: "Index",
  components: {},
  data() {
    return {
      searching: false,
      // 扫描到的设备
      devices: [],
      // 过滤最小信号强度
      filterRssi: -100,
      // 过滤名称
      filterName: "",
      // 是否显示filter
      showFilter: false,
      // btManager
      bt: null,
      scanTimer: null,
    };
  },
  computed: {},
  methods: {
    doSearch() {
      if (!this.searching) {
        this.scan();
      } else {
        this.stopScan();
      }
    },
    initBluetooth() {
      // 初始化蓝牙管理器
      this.bt = new BTManager({
        debug: true,
      });
      // 注册状态回调
      this.bt.registerDidUpdateConnectStatus(
        this.didUpdateConnectStatus.bind(this)
      );
      // 注册发现外设回调
      this.bt.registerDidDiscoverDevice(this.didDiscoverDevice.bind(this));
    },
    didUpdateConnectStatus(res) {
      console.log("home registerDidUpdateConnectStatus", res);
      if (res.connectStatus === ConnectStatus.connected) {
        set("curr_bledev", res.device);
        Taro.hideLoading();
        Taro.navigateTo({
          url: "/pages/btDetail/index?device=" + JSON.stringify(res.device),
        });
      } else if (res.connectStatus === ConnectStatus.disconnected) {
        Taro.hideLoading();
        // 从详情页面返回的话，不提示了
        let last_bledev = get("curr_bledev");
        if (last_bledev && res.device.deviceId == last_bledev.deviceId) {
          console.log("find-lastdev: ", res.device.deviceId);
          if (
            SuccessCallbackEvent.Success_ConnectStatus_CB_Stop.code == res.code
          ) {
            console.log("quite-disconnect：", res.device.deviceId);
            return;
          }
        }
        // 其他情况进行提示
        Taro.showToast({
          title: res.message,
          icon: "none",
          duration: 2000,
        });
      }
    },
    didDiscoverDevice(res) {
      // console.log('home didDiscoverDevice', res);
      if (res.timeout) {
        console.log("home didDiscoverDevice", "扫描超时");
        Taro.showModal({
          content: "扫描超时",
          showCancel: false,
        });
      } else {
        let device = res.device;
        let devices = this.devices;
        // 检查重复上报设备，更新信息
        function checkDuplicateDevice(d, ds) {
          for (let v of ds) {
            if (v.deviceId === d.deviceId) {
              Object.assign(v, d);
              return true;
            }
          }
          return false;
        }
        // 更新 & 过滤
        if (
          !checkDuplicateDevice(device, devices) &&
          device.RSSI >= this.filterRssi
        ) {
          devices.push(device);
        }
        this.devices = devices;
      }
    },
    scan() {
      this.searching = true;
      this.devices = [];
      function scanDevice() {
        this.bt
          .scan({
            services: [],
            allowDuplicatesKey: false,
            interval: 0,
            timeout: 15000,
            deviceName: "",
            containName: this.filterName,
          })
          .then((res) => {
            console.log("home scan success", res);
          })
          .catch((e) => {
            console.log("home scan fail", e);
            this.destoryTimer();
            Taro.showToast({
              title: e.message,
              icon: "none",
            });
          });
      }
      scanDevice.call(this);
      // 重复调用前先销毁之前的计时器
      this.destoryTimer();
      this.scanTimer = setInterval(scanDevice.bind(this), 5000);
    },
    stopScan() {
      this.searching = false;
      this.destoryTimer();
      this.bt
        .stopScan()
        .then((res) => {
          console.log("home stopScan success", res);
        })
        .catch((e) => {
          console.log("home stopScan fail", e);
        });
    },
    destoryTimer() {
      this.scanTimer && clearInterval(this.scanTimer);
      this.scanTimer = null;
    },
    connectDevice(device) {
      this.stopScan();
      this.bt
        .connect(device)
        .then((res) => {
          console.log("home connect success", res);
        })
        .catch((e) => {
          Taro.showToast({
            title: e.message,
            icon: "none",
            duration: 2000,
          });
          console.log("home connect fail", e);
        });
      Taro.showLoading({
        title: "连接" + device.name || "未知设备",
      });
    },
  },
  mounted() {},
  onReady() {},
  onShow() {
    this.initBluetooth();
  },
  onHide() {
    this.stopScan();
  },
  onUnload() {
    this.stopScan();
  },
  unmounted() {
    this.stopScan();
  },
};
</script>

<style lang="scss">
.dev-list {
  padding: 10px;
}
.dev-item {
  padding: 10px 0;
  border-bottom: 1px solid #cdd;
}
.dev-name {
  font-size: 16px;
}
.dev-id {
  font-size: 12px;
  color: #aaa;
}
.dev-signal {
  font-size: 12px;
  color: #080;
}
.dev-service {
  font-size: 12px;
  color: #333;
}

.dev-next {
  padding-top: 40px;
}
</style>
